<template>
    <div class="app-container">
        <el-form :model="queryParams" ref="queryRef" v-show="showSearch" :inline="true">
            <el-form-item label="宿舍" prop="dormId">
                <el-select v-model="queryParams.dormName" class="m-2" placeholder="请选择宿舍">
                    <el-option v-for="item in dorms" :key="item.id" :label="item.dormName" :value="item.dormName" />
                </el-select>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" icon="Search" size="mini" @click="getList">搜索</el-button>
                <el-button icon="Refresh" size="mini" @click="resetQuery">重置</el-button>
            </el-form-item>
        </el-form>

        <el-row :gutter="10" class="mb8">
            <el-col :span="1.5">
                <el-button type="primary" plain icon="Plus" size="mini" @click="handleAdd"
                    v-hasRole="['dormManagement2']">新增</el-button>
            </el-col>
            <el-col :span="1.5">
                <el-button type="danger" plain icon="Delete" size="mini" @click="handleDelete"
                    v-hasRole="['dormManagement']">删除</el-button>
            </el-col>
            <el-col :span="1.5">
                <el-button type="warning" plain icon="Download" size="mini" @click="handleExport"
                    v-hasRole="['dormManagement']">导出</el-button>
            </el-col>
            <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>

        <!-- 表格数据 -->
        <el-table v-loading="loading" :data="studentInfoList" stripe border @selection-change="handleSelectionChange">
            <el-table-column type="selection" width="50" />
            <el-table-column label="宿舍" prop="dormName" :show-overflow-tooltip="true" width="80" sortable />
            <el-table-column label="姓名" prop="name" :show-overflow-tooltip="true" width="80" sortable />
            <el-table-column label="床位" prop="bedId" :show-overflow-tooltip="true" width="80" sortable />
            <el-table-column label="入住时间" prop="checkInTime" :show-overflow-tooltip="true" width="120" sortable />
            <el-table-column label="专业" prop="specialized" :show-overflow-tooltip="true" width="140" sortable />
            <el-table-column label="手机号" align="center" :show-overflow-tooltip="true" prop="phone" width="120" sortable />
            <el-table-column label="添加者" align="center" :show-overflow-tooltip="true" prop="addName" width="100" sortable />
            <el-table-column label="添加时间" align="center" :show-overflow-tooltip="true" prop="addTime" width="160"
                sortable />
            <el-table-column label="修改者" align="center" :show-overflow-tooltip="true" prop="modifyName" width="100"
                sortable />
            <el-table-column label="修改时间" align="center" :show-overflow-tooltip="true" prop="modifyTime" width="160"
                sortable />
            <el-table-column label="操作" fixed="right" align="center" class-name="small-padding fixed-width" width="80">
                <template #default="scope">
                    <el-button size="mini" type="text" @click="updateShow(scope.row)"
                        v-hasRole="['dormManagement2']">修改</el-button>
                </template>
            </el-table-column>
        </el-table>

        <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum"
            v-model:limit="queryParams.pageSize" @pagination="getList" />

        <el-dialog :title="title" v-model="open" width="400px">
            <el-form ref="formRef" :model="addForm" :rules="rules2" label-width="80px">
                <el-form-item label="宿舍" prop="dormId" v-if="title == '添加宿舍财产'">
                    <el-select v-model="addForm.dormId" class="m-2" placeholder="请选择宿舍">
                        <el-option v-for="item in dorms" :key="item.id" :label="item.dormName" :value="item.id" />
                    </el-select>
                </el-form-item>
                <el-form-item label="财产名称" prop="propertyName">
                    <el-input v-model="addForm.propertyName" placeholder="请输入财产名称" style="width: 16vw;" />
                </el-form-item>
                <el-form-item label="财产数量" prop="propertyNumber">
                    <el-input-number v-model="addForm.propertyNumber" :min="1" :max="1000" @change="handleChange" />
                </el-form-item>
            </el-form>
            <el-form class="btnGroup">
                <el-button size="large" :loading="btnLoading" type="primary" @click="submit">确 定</el-button>
                <el-button size="large" @click="cancel">取 消</el-button>
            </el-form>
        </el-dialog>
    </div>
</template>

<script setup name="dormManagementStudentLodging">
import { ElNotification } from 'element-plus'
import { getStudentDormInfoApi, getDormApi, addDormPropertyApi, deleteStudentDormApi, updateDormPropertyApi } from '@/api/dormMangement'
import { exportExcel } from '@/utils/excelExport'
const router = useRouter();
const { proxy } = getCurrentInstance();

const studentInfoList = ref([]);
const open = ref(false);
const loading = ref(true);
const btnLoading = ref(false);
const showSearch = ref(true);
const ids = ref([]);
const title = ref('')
const total = ref(0);

const data = reactive({
    form: {},
    queryParams: {
        pageNum: 1,
        pageSize: 10,
        dormName: undefined
    }
});

const { queryParams, form } = toRefs(data);

const data2 = reactive({
    addForm: {
        dormId: '',
        propertyName: '',
        propertyNumber: 1
    },
    rules2: {
        dormId: [{ required: true, message: "宿舍不能没有选择", trigger: "blur" }],
        propertyName: [{ required: true, message: "财产名称不能为空", trigger: "blur" }],
        propertyNumber: [{ required: true, message: "财产数量不能为空", trigger: "blur" }]
    },
});

const { addForm, rules2 } = toRefs(data2)

const dorms = ref([])

const getDorms = () => {
    getDormApi().then(res => {
        if (res.code == 200) {
            dorms.value = res.data
        }
    })
}
getDorms()

const getList = () => {
    loading.value = true
    getStudentDormInfoApi(queryParams.value).then(res => {
        if (res.code == 200) {
            studentInfoList.value = res.data.vo
            loading.value = false
            total.value = res.data.total
        } else {
            studentInfoList.value = []
            loading.value = false
        }
    }).catch(err => {
        studentInfoList.value = []
        loading.value = false
    })
}
getList()

const submit = () => {
    proxy.$refs["formRef"].validate(valid => {
        if (valid) {
            btnLoading.value = true
            console.log(addForm.value);
            if (title.value == "添加宿舍财产") {
                addDormPropertyApi(addForm.value).then(res => {
                    if (res.code == 200) {
                        ElNotification({
                            title: '提示',
                            message: '添加成功',
                            type: 'success'
                        })
                        getList()
                        cancel()
                    }
                }).catch(err => {
                    btnLoading.value = false;
                })
            } else if (title.value == "编辑宿舍财产") {
                console.log(addForm.value);
                updateDormPropertyApi(addForm.value).then(res => {
                    if (res.code == 200) {
                        ElNotification({
                            title: '提示',
                            message: '修改成功',
                            type: 'success'
                        })
                    }
                    getList()
                    cancel()
                }).catch(err => {
                    btnLoading.value = false;
                })
            }
        }
    })
}

const handleDelete = () => {
    if (ids && ids.value.length > 0) {
        let id = ""
        console.log(ids.value);
        console.log(ids.value.length);
        proxy.$modal.confirm('是否确认删除选中的数据项?').then(function () {
            if (ids && ids.value.length > 0) {
                for (let i = 0; i < ids.value.length; i++) {
                    if (i <= ids.value.length - 2) {
                        id += ids.value[i] + ","
                    } else if (i == ids.value.length - 1) {
                        id += ids.value[i]
                    }
                }
            }
            return deleteStudentDormApi(id)
        }).then(() => {
            getList();
            ElNotification({
                title: '提示',
                message: '删除成功',
                type: 'success'
            })
        }).catch(() => { });
    } else {
        proxy.$modal.msgWarning("请选择要删除的数据项");
    }
}

const updateShow = (row) => {
    open.value = true
    title.value = '编辑宿舍财产'
    addForm.value = row
}

const resetQuery = () => {
    proxy.resetForm("queryRef")
    queryParams.value.dormName = ''
}

const cancel = () => {
    open.value = false
    btnLoading.value = false
    proxy.resetForm("formRef")
    addForm.value = ''
}

const handleAdd = () => {
    open.value = true
    title.value = '添加宿舍财产'
}
/** 导出按钮操作 */
function handleExport() {
    let arr = []
    studentInfoList.value.forEach(item => {
        let out = {}
        out.dormName = item.dormName;
        out.name = item.name;
        out.bedId = item.bedId;
        out.checkInTime = item.checkInTime;
        out.specialized = item.specialized;
        out.phone = item.phone;
        out.addTime = item.addTime;
        out.addName = item.addName;
        out.modifyTime = item.modifyTime;
        out.modifyName = item.modifyName
        arr.push(out)
    })
    const titleArr = ['宿舍', '姓名', '床位', '入住时间', '专业', '手机号', '创建时间', '创建者', '最后修改时间', '最后修改者']  //表头中文名
    exportExcel(arr, '学生住宿信息', titleArr, 'Sheet1')
}
const handleChange = (val) => {
    addForm.value.propertyNumber = val
}

/** 多选框选中数据 */
const handleSelectionChange = (selection) => {
    ids.value = selection.map(item => item.id)
}
</script>
